﻿﻿/***************************  Ccay IGrid Pager  ***********************************/
(function(IGrid){
	var pagerMsg = IGrid.Const.I18n.pager = {
		pagerSave : "ccay.common.message.confpagersave",
		noResult : 'ccay.common.label.noresult',
		validLose : 'ccay.common.igrid.pagervalidlose'
	};
	
	var GridPager = {
	   //初始化分页控件
	   initPager:function(grid, op){
	   		//grid.getBodyPanel().addClass("animated");
	   		!op.pagerOp && (op.pagerOp = {});
	   		var pager = $.create("div", "", grid.id + "Pager").appendTo(grid.getBottom()),
	    		fnBeforeChanged = op.pagerOp.fnBeforeChanged;
		    op.pagerOp.fnBeforeChanged = function (pager, pageInf, oldPage, oldPageSize, fnChange, oldTotalPages) {
		    	if (!fnBeforeChanged || fnBeforeChanged(pager, pageInf, oldPage, pageInf.pageSize, fnChange, oldTotalPages) !== false) {
			       	var storage = op.Storage, data = storage.getChangedRecords();
					if (!op._cache && (data.insertedRecords.length || data.updatedRecords.length || data.deletedRecords.length)) {
						Ccay.UI.confirm(pagerMsg.pagerSave, function(result) {
							if (result) {
								var saveBtn = op.operation && op.operation.save && op.operation.save.btn;
								if(grid.valid() && saveBtn) {
									$(saveBtn).click();
								} else {
									pageInf.curPage = oldPage;
									pageInf.pageSize = oldPageSize;
									pageInf.totalPages = oldTotalPages;
									//修复iGrid页码提示保存，同步保存，保存后不显示页码。
									fnChange(pager, pageInf);
									Ccay.UI.showMessage(pagerMsg.validLose, "warn");
								}
							}
							else{
								fnChange(pager, pageInf);
								op.pagerOp.pageInf = pageInf;
								grid.reload(false, true, true);
							}
						}, true);
					} else {
						fnChange(pager, pageInf);
						op.pagerOp.pageInf = pageInf;
						grid.reload(false, true, true);
					}
		    	}
		    	return false;
		    };
	       	pager.pager(op.pagerOp, grid);
	       	op.handler.afterBindData.add(function (grid, op) {
	       			//animate test by zhanghu
//	       			grid.getBodyPanel().addClass("rotateIn");
//			       	setTimeout(function(){
//							grid.getBodyPanel().removeClass("rotateIn");
//					},2000);
				// 存在重新加载的标示，则不执行分页信息操作
   				op._reload || grid.getBottom().children('.ccay-pager').pager(op.pagerOp, grid);
			});
	   },
	   //初始化滚动加载组件
	   initScrollPager:function(grid, op,datas){
	   		//关闭刷新后的滚动重置设置
	   		op.autoScroll = null;
	   		//ajax请求模式下，设置为服务端排序
	   		op.ajax && (op.remoteSort = true);
	   		//新插入行序号设置
	   		//op.rowCodeBegin.push(" data._inserted && index--;");
	   		//建立分页信息数据映射对象
	   		op._scrollOp = {
	   			start:1,
	   			end:op.pagerOp.pageInf.pageSize,
	   			pageSize:op.pagerOp.pageInf.pageSize,
	   			total:op.pagerOp.pageInf.totalRows
	   		};
	   		var isAjaxLoad = grid.op.lazyLoad != 'filter' && op.ajax,loadingShowed,
	   			scrollOp = {
		   			itemHeight: op.rowHeight,
		   			pageInf:op._scrollOp,
		   			mode: isAjaxLoad ? 'ajax' : 'filter',
		   			dataParam: isAjaxLoad ? op.ajax : op.handler.dataProcess,
		   			target:grid.getBodyPlace(),
		   			fnLoad:function(pageInf){
		   				grid.op.ajax && (grid.op.ajax.loading = false);
		   				grid.op._scrollLoading = true;
		   				grid.getBodyTable().hide();
						grid.reload(false, grid.op.lazyLoad != 'filter');
						grid.op._scrollLoading = false;
		   			}
		   		};
		   	
		   	if(isAjaxLoad)
		   	{//ajax模式下
		   		scrollOp.fnTriggeOver = function(scroller,start,end){
		   			// 修复新增行显示编辑器，页面加载时，还显示编辑器的问题
		   			grid.clearActiveEditor();
		   			grid.getBodyTable().hide();
	   				if(!loadingShowed)
	   				{
		   				var pos = scroller.offset(),
		   					loading = Ccay.UI.loading();
		   				loading.css({top:pos.top + (scroller.height() - 80)/ 2,left:pos.left + (scroller.width() - 200)/ 2 });
	   					loadingShowed = true;
	   				}
	   			}
	   			scrollOp.fnScrollEnd = function(scroller,pageInf,isLoad){
	   				if(!isLoad)
	   				{
	   					// 未加载下，显示数据集
	   					grid.getBodyTable().show();
	   					Ccay.UI.loadingClose();
	   					loadingShowed = null;
	   				}
	   			}
		   	}
		   	else
		   	{//静态数据过滤模式
		   		scrollOp.delay = 0;
		   		// 若存在获取index方法，则不重写
		   		if (!grid._getRowIndex) {
			   		//重写根据获取index方法
			   		grid._getRowIndex = grid.getRowIndex;
			   		grid.getRowIndex = function(tr){
			   			var index = this._getRowIndex(tr);
			   			if(index > -1)
			   				return index + op.startIndex - 1;
			   			return index;
			   		}
		   		}
		   	}
	   		var scrollLoader = op.scrollLoader = grid.getBodyPanel().scrollLoad(scrollOp),
	   			// 创建滚动加载的页数信息
	   			scrollPager = $.create("div", "ccay-pager ccay-pager-number").appendTo(grid.getBottom());
	   		// 绑定数据前执行设置分页信息
			op.handler.beforeBindData.add(function (grid, op) {
				GridPager.setPageInf(grid, op);
				if (op._scrollTop) {
	    			grid.getBodyPanel().scrollTop(op._scrollTop);
	    			op._scrollTop = null;
	    		}
			});
			// 绑定数据后执行设置滚动总数
	   		op.handler.afterBindData.add(function(grid,op){
	    		scrollLoader.setTotal(op.pagerOp.pageInf.totalRows);
	    		grid.getBodyTable().show();
	    		scrollPager.html(GridPager.setScrollPager(grid, op));
				if(loadingShowed)
				{
		    		Ccay.UI.loadingClose();
		    		loadingShowed = null;
				}
			});

	   		if(op.operation)
	   		{
	   			//查询操作清空分页信息处理
	   			op.operation.search && op.handler.beforeLoad.add(function(grid,op,isSearch){
			   		if (isSearch) {
			   			op.ajax && (op.ajax.loading = true);
			   			scrollLoader.reset();
			   		}
	   			});
	   			//自定义新增操作的参数
	   			op.operation.insert && (op.operation.insert._getInsertSet = GridPager.getInsertSet);
	   		}
	   },
	   /** @description 设置滚动分页信息
	    *  @param {Object} grid IGrid对象
		*  @param {Object} op grid的配置信息 
	    */
	   setScrollPager: function (grid, op) {
		   grid.getBodyPanel().find(".grid-no-result").remove();
	   		var html = [], totalRows = op.pagerOp.pageInf.totalRows;
	   		if (totalRows > 0) {
	   			html.push('<div class="ccay-pager-group msg">',
					Ccay.UI.Config.pager.text.total.formatText("<font class='total'>" + totalRows + "</font>"), '</div>');
	   		} else {
	   		//如用户设置自定义提示，则显示自定义提示
				if(null != op.noResultI18n){
					pagerMsg.noResult = op.noResultI18n;
				}
	   			grid.getBodyPanel().append('<div class="grid-no-result">'+$i18n(pagerMsg.noResult)+'</div>');
	   		}
	   		return html.join("");
	   },
	   setPageInf:function(grid, op){
			op.startIndex = op._scrollOp.start;
//			if(op.ajax)
//			{
				var pageInf = op.pagerOp.pageInf;
				pageInf.pageSize = op._scrollOp.pageSize;
				pageInf.curPage = parseInt(op.startIndex / pageInf.pageSize) + 1;
//			}
	   },
	   getInsertSet:function(grid,op){
	   		var setting = {scroll : false},posTr = grid.getFocusRow();
	   		// 选中复制定位
	   		if (grid.getSelectedRecords().length)
	   		{
	   			while(posTr.length) {
	   				var posTrPrev = posTr.prev();
	   				if (posTrPrev.hasClass("igrid-selected")) {
	   					posTr = posTrPrev;
	   				} else {
	   					break;
	   				}
	   			}
	   		} 
	   		if(posTr && posTr.length)
	   		{
	   			setting.posTr = posTr;
	   		}
	   		else if (op._scrollOp.showStart && op._scrollOp.showStart > 1)
	   		{
	   			var startTr = grid.getRow(op._scrollOp.showStart % op._scrollOp.pageSize);
		   		if(startTr.length)
		   		{
		   			posTr = startTr;
		   			for(var i = op._scrollOp.showStart;i < op._scrollOp.showEnd;i++)
		   			{
		   				if(grid.isNewRow(posTr))
		   				{
		   					setting.posTr =  posTr;
		   					break;
		   				}
		   				posTr = startTr.next();
		   			}
		   			setting.posTr || (setting.posTr = startTr);
		   		}
	   		}
	   		if(setting.posTr)
	   		{
	   			var posTr = setting.posTr;
	   			// 修复滚动加载模式下，新增后再加载数据错位问题
	   			while(posTr.length) {
	   				if (grid.isNewRow(posTr) && posTr.next().length) {
	   					posTr = posTr.next();
	   				} else {
	   					break;
	   				}
	   			} 
	   			var rowData = grid.getRowData(posTr);
	   			//setting.posIndex = op.Storage.isNew(rowData) ? rowData._index : op._scrollOp.showStart + 1;
	   			setting.posIndex = rowData._index;
	   		}
	   		else
	   			op._scrollOp.showStart > 1 && (setting.posIndex = op._scrollOp.showStart + 1);

//	   		setting.dataHandle = function(record,grid){
//	   			record._posIndex = this.posIndex;
//	   			if(this.posIndex)
//	   			{
//		   			var newData = grid.op._scrollOp.newData,posData = newData[this.posIndex];
//		   			if(posData)
//		   				newData[this.posIndex].push(record);
//		   			else
//		   				newData[this.posIndex] = [record];
//	   			}
//			}
	   		return setting;
	   }
	};
	
	Ccay.UI.XControl.addPlugin("XGrid", "pager", {
	    build: function (grid, op) {
	    	if(op.showPager){
	    		op.lazyLoad ? GridPager.initScrollPager(grid, op, op.dataset) 
							: GridPager.initPager(grid, op);
	    	}
	    }
	});
})(Ccay.UI.IGrid);